package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper ,Emp> implements EmpService {
    @Resource
    private DeptService deptService;
    @Resource
    private EmpExprService empExprService;


    @Override
    public PageResult<Emp> getPageResult(EmpQueryParam param){
        //创建分页模型对象，设置页码和每页数量
        Page<Emp> page =Page.of(param.getPage(),param.getPageSize());

        //添加排序条件，根据最后修改时间排序
        page.addOrder(OrderItem.desc("update_time"));

        // ↓↓↓准备分页搜索的条件↓↓↓
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(param.getName() != null && !param.getName().isEmpty(), Emp::getName, param.getName())
                .eq(param.getGender() != null, Emp::getGender, param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null, Emp::getEntryDate, param.getBegin(), param.getEnd());


        //调用 从父类里继承来的page方法完成分页查询
        page = page(page,queryWrapper);
        //封装结果并返回

        //为每个员工补齐 部门名称
        //获取员工集合
        List<Emp> emps = page.getRecords();
        //获取所有员工的部门id
        List<Integer> deptIds = emps.stream().map(emp -> emp.getDeptId()).collect(Collectors.toList());

        //批量查询这些部门的信息，并转化成Map <部门id，部门名称>
        List<Dept> depts = deptService.listByIds(deptIds);

        Map<Integer,String> deptNames=depts.stream()
                .collect(Collectors.toMap(Dept::getId,Dept::getName));

        //将部门名称封装进员工对象中
        emps.forEach(emp -> emp.setDeptName(deptNames.get(emp.getDeptId())));

        return new PageResult<>(page.getTotal(),page.getRecords());
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveEmp(Emp emp){
        //调用service层方法保存员工信息
        //补全基础属性
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());

        save(emp);

        //调用service层方法保存员工工作经历
        List<EmpExpr> empExprs =  emp.getExprList();


        //添加工作经历所属员工
        empExprs.forEach(expr -> expr.setEmpId(emp.getId()));
        empExprService.saveBatch(empExprs);

    }


    //查询回显
    @Override
    public Emp getEmpById(Integer id){
        Emp emp = getById(id);

        //添加工作经历
        emp.setExprList(empExprService.list(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId,id)));
        return emp;
    }

    //修改
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmp(Emp emp){
        emp.setUpdateTime(LocalDateTime.now());
        updateById(emp);


        //删除员工工作经历
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId,emp.getId()));


        //批量保存员工工作经历
        List<EmpExpr> empExprs = emp.getExprList();
        if (empExprs !=null  && !empExprs.isEmpty()){
            empExprs.forEach(expr ->expr.setEmpId(emp.getId()));
        }
empExprService.saveBatch(empExprs);
    }


    //删除
    @Override
    @Transactional(rollbackFor=Exception.class)
    public void removeByIds(List<Integer> ids){
 if(ids == null  || ids.isEmpty()){
   return;
 }

 //调用service方法删除员工信息
 removeBatchByIds(ids);

 //删除员工工作经历
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>()
                .in(EmpExpr::getEmpId,ids));

    }

}
